package org.liaohailong.library.widget.shopping.recycler;

import android.util.SparseArray;
import android.view.View;

import androidx.annotation.NonNull;

import java.util.LinkedList;

/**
 * Author: Victor
 * E-mail: liaohailong190@foxmail.com
 * Date: 2019/6/22 16:43
 * Description: 对象复用池
 */
public class RecyclerPool {

    /**
     * 单种ViewType的最大缓存数量
     * 总数量 = maxSize * 总ViewType
     */
    private int maxSize = 5;

    private SparseArray<LinkedList<View>> mRecyclerViews = new SparseArray<>();

    @NonNull
    public View obtainView(int viewType) {
        LinkedList<View> views = mRecyclerViews.get(viewType);
        if (views == null) {
            views = new LinkedList<>();
            mRecyclerViews.put(viewType, views);
        }
        return views.removeFirst();
    }

    public void recycleView(int viewType, View view) {
        LinkedList<View> views = mRecyclerViews.get(viewType);
        if (views == null) {
            views = new LinkedList<>();
            mRecyclerViews.put(viewType, views);
        }
        if (views.size() < maxSize) {
            views.addLast(view);
        }
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public int getMaxSize() {
        return maxSize;
    }
}
